const fs = require('fs');
const path = require('path');
const regScript = /<script>[\s\S]*<\/script>/; //\s 匹配空行 \S 匹配任意字符 
const regStyle = /<style>[\s\S]*<\/style>/;

fs.readFile(path.join(__dirname, './index.html'), 'utf-8', function(err, datastr) {
    if (err) {
        return console.log('读取失败' + err.message);
    }
    // console.log(datastr);
    resolveStyle(datastr)
    resolveScript(datastr);
    resolveHtml(datastr);
})

//提取css
function resolveStyle(data) {
    const newStyle = regStyle.exec(data);
    const newStyle2 = newStyle[0].replace('<style>', '').replace('</style>', '')
    console.log(newStyle2);
    fs.writeFile(path.join(__dirname, './clock/index.css'), newStyle2, function(err) {
        if (err) { return }
        console.log('输入成功');
    })
}

//提取js
function resolveScript(data) {
    //通过正则去匹配数据
    const newScript = regScript.exec(data);
    //将script标签去除
    const newScript2 = newScript[0].replace('<script>', '')
        .replace('</script>', '')
        // console.log(newScript2);
        //写入文件
    fs.writeFile(path.join(__dirname, './clock/index.js'),
        newScript2,
        function(err) {
            if (err) { return }
            console.log('输入成功');
        })
};

//提取html
function resolveHtml(data) {
    //将内联的link换成外联link script也是
    const htmlnew = data.replace(regStyle, '<link rel="stylesheet" href="./index.css">')
        .replace(regScript, '<script src="./index.js"></script>')
    fs.writeFile(path.join(__dirname, './clock/index.html'), htmlnew, function(err) {
        if (err) { return }
        console.log('输入成功');
    })
}